package xyz.xtt.gateway;

import static java.util.stream.Collectors.joining;

import java.net.URI;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class LogGlobalFilter implements GlobalFilter, Ordered {

	@Override
	public int getOrder() {
		return -1;
	}

	@Value("${run.mode.showHeader:false}")
	private Boolean showHeader;

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		showHeader(exchange);
		return chain.filter(exchange);
	}

	private void showHeader(ServerWebExchange exchange) {
		if (showHeader) {
			URI uri = exchange.getRequest().getURI();
			log.info("LogGlobalFilter uri: {}", uri);
			ServerHttpRequest request = exchange.getRequest();
			HttpHeaders headers = request.getHeaders();
			Set<Entry<String, List<String>>> entrySet = headers.entrySet();
			entrySet.forEach(x -> {
				String key = x.getKey();
				List<String> values = x.getValue();
				String value = values.stream().collect(joining(","));
				log.info("{}={}", key, value);
			});
		}
	}
}
